//
//  TogetherBuyViewControllerDetail.m
//  PlayBall
//
//  Created by Jdd‘s macbook on 13-9-26.
//
//

#import "JddTogetherBuyViewControllerDetail.h"
#import "JddTogetherBuyViewController.h"
#import "JddViewControllerManager.h"
#import "JddBuyDetailViewController.h"
@interface JddTogetherBuyViewControllerDetail ()

@end

@implementation JddTogetherBuyViewControllerDetail

- (void)loadLine
{
    CGRect frame = self.line1.frame;
    frame.size.height = 0.5;
    self.line1.frame = frame;
    
    frame = self.line2.frame;
    frame.size.height = 0.5;
    self.line2.frame = frame;
    
    frame = self.line3.frame;
    frame.size.height = 0.5;
    self.line3.frame = frame;
    
    self.seeFangAnView.layer.borderColor = BORDER_COLOR;
    self.seeFangAnView.layer.borderWidth = 0.5;
    
    self.scrollView.frame = CGRectMake(0, 50, SCREEN_WIDTH, self.view.frame.size.height-45-55-50);
    
}
//- (void)backView
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:249/255.0f green:249/255.0f blue:249/255.0f alpha:1.0];

    [self loadLine];

    //不遮挡键盘
//    [self setScroll];
    self.moneyText.delegate = self;
    JddTogetherBuyViewController *tbv = (JddTogetherBuyViewController *)self.fromController;
    self.uName.text = tbv.uName;
    self.jd.text = tbv.jd;
    self.SchemeID = tbv.SchemeID;
    self.EndTime = tbv.EndTime;
    self.Share = tbv.Share;

    NSString *level = tbv.level;
    UIImage *levelImg = [JddCommonFunction getImgByLevel:level];
    [self.levelIV setImage:levelImg];
    [self.levelIV layoutToRightOf:self.uName AndSpace:3];
    
    //计算等级图标的宽
    CGFloat wid; //= [level integerValue]%5*15;
    if ([level integerValue]%5 == 0) {
        wid = 5*14;
    } else {
        wid = [level integerValue]%5*15;
    }
    //获取等级图片
    self.levelIV.frame = CGRectMake(self.levelIV.frame.origin.x, 81, wid, 14);
//    self.levelIV.Image = levelImg;
}

//-(void)setScroll{
//    CGRect contentRect = CGRectZero;
//    for ( UIView *subview in self.scrollView.subviews ) {
//        contentRect = CGRectUnion(contentRect, subview.frame);
//    }
//    if (SCREEN_HEIGHT > 480) {
//        self.scrollView.frame = CGRectMake(0, 50, SCREEN_WIDTH, 332+30);
//    }
//    self.scrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width, CGRectGetMaxY(contentRect));
//}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
   // [self.navigationItem setTitle:PAGE_TOGETHER_BUY_DETAIL];
    [MobClick beginLogPageView:@"TogetherBuy-detail"];
    [MobClick event:@"TAB-togetherbuy-detail"];

        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:PAGE_TOGETHER_BUY_DETAIL];
        customLab.textAlignment = NSTextAlignmentCenter;

        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
    
    //初始化数据
    [self initData];    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"TogetherBuy-detail"];
}
//添加方案内容子视图
-(void)addContentViewWithBuydetail:(NSDictionary *)buydetail
{
    JddBuyDetailViewController *contentView = [[JddBuyDetailViewController alloc] init];
    contentView.buydetail = buydetail;
    contentView.parentType = 1;
    [self addChildViewController:contentView];
    [self.contentView addSubview:contentView.view];

}
//方案宣传
- (void)customPlanXuanYanHeight:(NSString *)description
{
    if ([description length] != 0) {
        self.xuanYanLabel.text = description;
        JddSportNumber *str = [[JddSportNumber alloc] init];
        str.titleStr = description;
        CGRect frame = self.xuanYanLabel.frame;
        frame.size.height = [str customHeight:220.f font:12] + 40;
        self.xuanYanLabel.frame = frame;
        
        //多出来的高度
        CGFloat space = frame.size.height - 50;
        CGRect bgMoveFrame = self.bgMoveView.frame;
        bgMoveFrame.size.height += space;
        self.bgMoveView.frame = bgMoveFrame;
        
        CGRect rect = self.seeFangAnView.frame;
        rect.origin.y = frame.origin.y + frame.size.height;
        self.seeFangAnView.frame = rect;
        
        CGRect rect2 = bgMoveFrame;
        rect2.size.height += 20;
        self.scrollView.contentSize = rect2.size;
    } else {
        self.xuanYanLabel.text = @"这个方案会中大奖的，至于你信不信，反正我信了!";
    }

}
//解析大厅传进来的数据
-(void)initData
{
    NSDictionary *buydetail = [self.realString objectFromJSONString];
    float jinDu = [[self.buyHallData objectForKey:@"Schedule"] floatValue];
    if (jinDu >= 100.0f) {
        self.lijiBuyBtn.enabled = NO;
    }
    
    //方案宣传
    [self customPlanXuanYanHeight:[buydetail objectForKey:@"Description"]];

    //设置方案内容view高度
    CGRect viFrame = self.contentView.frame;
    if (SCREEN_HEIGHT > 480) {
        viFrame.size.height = 200;

    } else {
        viFrame.size.height = 120;
    }
    
    viFrame.origin.y = self.seeFangAnView.frame.size.height+self.seeFangAnView.frame.origin.y - viFrame.size.height;
    self.contentView.frame = viFrame;
    self.contentView.hidden = YES;
    [self addContentViewWithBuydetail:buydetail];
    
//    BOOL isMyWinMoney;
    NSString *lottName = [buydetail objectForKey:@"LottName"];
    if ([lottName isEqualToString:@"超级大乐透"]) {
        lottName = @"大乐透";
    }
    [self loadIconView:lottName];
    NSString *secState = [buydetail objectForKey:@"SecState"];
    NSInteger schedule = [[self.buyHallData objectForKey:@"Schedule"] integerValue];
    CGRect frame = self.baiFenHao.frame;
    if (schedule > 99 ) {
        frame.origin.x = 75;
    } else if (schedule < 10) {
        frame.origin.x = 57;
    }
    self.baiFenHao.frame = frame;
    NSString *issue = [NSString stringWithFormat:@"第%@期",[buydetail objectForKey:@"Issue"]];
    NSString *money = [buydetail objectForKey:@"Money"];//总金额
    NSString *am0 = [[buydetail objectForKey:@"AM"] stringByReplacingOccurrencesOfString:@"," withString:@""];
    NSString *amm = [[am0 componentsSeparatedByString:@"."] firstObject];
    NSString *am = [NSString stringWithFormat:@"%@彩豆", amm];
    NSString *buyEndTime = [buydetail objectForKey:@"BuyEndTime"];
    NSString *bonus = [NSString stringWithFormat:@"%@%@",[[buydetail objectForKey:@"Bonus"] stringValue],@"%"];
    NSString *mc = [NSString stringWithFormat:@"%@人", [buydetail objectForKey:@"MC"]];//跟单人数
    NSString *state = [buydetail objectForKey:@"State"];
//    NSString *myWinMoney = [NSString stringWithFormat:@"%@", [buydetail objectForKey:@"MyWinMoney"]];
    int bs = [[buydetail objectForKey:@"BS"] intValue];
    //可购金额
    fMoney = [[money stringByReplacingOccurrencesOfString:@"," withString:@""] floatValue];
    fMoney = fMoney - bs;
    
//    if (![myWinMoney isEqualToString:@""] && ![myWinMoney isEqualToString:@"0.00"] && ![myWinMoney isEqualToString:@"-"] && ![myWinMoney isEqualToString:@"0"]) {
//        isMyWinMoney = TRUE;
//    }
    
    NSString *shengyu = [[self.buyHallData objectForKey:@"RShare"] stringValue];
    NSString *baodibili = [NSString stringWithFormat:@"（%@%@）",[[buydetail objectForKey:@"Schedule"] stringValue],@"%"];
    self.shengyuLabel.text = shengyu;
    self.baodiBiliLabel.text = baodibili;//保底比例
    self.am.text = am;//保底金额
    [self.baodiBiliLabel layoutToRightOf:self.am AndSpace:0];
    self.jinDuLabel.text = [NSString stringWithFormat:@"%d",schedule];
    self.lottName.text = lottName;
    [self.isYsqLbl layoutToRightOf:self.lottName AndSpace:0];
    self.secState.text = secState;//方案保密状态
    self.state.text = state;
    self.issue.text = issue;
    self.money.text = money;
    self.buyEndTime.text = buyEndTime;
    self.bonus.text = bonus;
    self.mc.text = mc;
    self.kgMoney.text = [NSString stringWithFormat:@"%.0f", fMoney];
}

-(void)hideKeyBoard
{
    [self.view endEditing:NO];
}

//全包
-(IBAction)qbAction
{
    [self hideKeyBoard];
    self.moneyText.text = [NSString stringWithFormat:@"%0.01f", fMoney];
}

//购买
-(IBAction)buyAction
{
    if ([JddCommonFunction isLogin]) {
        int money = [self.moneyText.text intValue];
        int rShare = [[NSString stringWithFormat:@"%0.01f", fMoney] intValue];
        if (money == 0) {
            //金额不能为空
            [JddCommonFunction messageBoxWithMessage:TOGETHER_BUY_NOT_EMPTY];
        }else if(money > rShare){
            //不能超出认购金额
            [JddCommonFunction messageBoxWithMessage:TOGETHER_BUY_NOT_RSHARE];
        }else{
            [self hideKeyBoard];
            //确认购买
            [self joinToghterBuyAction];
            /*
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"                                                            message:TOGETHER_BUY_SURE
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:@"取消",nil ];
            [alert show];*/
        }
    }else{
    
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"  message:LOGIN_SURE
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:@"取消",nil ];
        [alert show];
    }
}
#pragma mark 方案内容显示
- (IBAction)zhanKaiFangAn:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
        self.contentView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.bgMoveView.frame;
            if (SCREEN_HEIGHT > 480) {
                frame.origin.y -= 219;
            } else {
                frame.origin.y -= 139;
            }
            self.bgMoveView.frame = frame;
        } completion:nil];
        self.scrollView.scrollEnabled = NO;
    } else {
        self.contentView.hidden = YES;
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.bgMoveView.frame;
            frame.origin.y = 0;
            self.bgMoveView.frame = frame;
        } completion:nil];
        self.scrollView.scrollEnabled = YES;

    }
}

- (IBAction)yunsuanButton:(UIButton *)sender
{
    int money = [self.moneyText.text intValue];
    if (sender.tag == 98 && money > 0) {
        money--;
    }
    if (sender.tag == 99 && money < [self.kgMoney.text intValue]) {
        money++;
    }
    self.moneyText.text = [NSString stringWithFormat:@"%d",money];

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([[alertView message] isEqualToString:LOGIN_SURE]) {
        if (buttonIndex == 0) {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN
                                                                 fromController:self
                                                                     withObject:nil
                                                                    withObject2:nil];
        }
    }else if ([[alertView message] isEqualToString:TOGETHER_BUY_SURE]) {
        if (buttonIndex == 0) {
            //参于合买
            [self joinToghterBuyAction];
        }
    }
}

-(void)joinToghterBuyAction
{
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    JddJoinTogetherBuyOperation *operation = [[JddJoinTogetherBuyOperation alloc] init];
    operation.delegate= self;
    operation.SchemeID = self.SchemeID;
    operation.DataSource = 1;
    operation.BuyShare = [self.moneyText.text intValue];
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}

-(void)initAlert
{
    alert1 = [JddTGAlertView getInstanceView];
    alert1.moneylable = [NSString stringWithFormat:@"%d彩豆", [self.moneyText.text intValue]];
    alert1.typestring = @"合买";
    alert1.lssueString = self.issue.text;
    alert1.faMoney = [NSString stringWithFormat:@"%d彩豆", self.Share];
    alert1.fromview = self;
    alert1.delegate = self;
}

-(void)JoinTogetherBuyOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    NSDictionary *resultStr = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
    
    [self initAlert];
//    if(result)
//    {
//        NSDictionary *ReDic = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
//        if([[ReDic objectForKey:@"Code"] intValue] == 0)
//        {
//            
//            NSString*checkUrlString = [NSString stringWithFormat:@"%@?ck=%@",BASE_SERVER_IOS_BUY_LOTTERY_URL,[ReDic objectForKey:@"Data"]];
//            NSURL *checkUrl = [NSURL URLWithString:checkUrlString];
//            [[UIApplication sharedApplication] openURL:checkUrl];
//        }
//        else
//        {
//            [JddCommonFunction messageBoxWithMessage:[ReDic objectForKey:@"Data"]];
//        }
//    }
    
    if (result)
    {
        if ([JddDataParser parseBuyResult:result]){
            //更新近期购买彩种
            NSString *name = self.lottName.text;
            [JddCommonFunction updateBuyLotteryListWithLotteryId:[JddCommonFunction getLotteryIdByName:name]];
            [alert1 alertMessage:@"认购成功"];
            }
        else {
            [alert1 alertMessage:[JddError sharedInstance].message];
        }
        [alert1 show];
    }
}

-(void)tbuy{
    [[JddViewControllerManager sharedInstance] popToBackViewController];
}
//根据彩种取彩种图标
- (void)loadIconView:(NSString *)lottName
{
//    self.lotteryIcon.frame = CGRectMake(10, 7, 35, 35);
    if ([lottName isEqualToString:@"竞彩足球"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_jc.png"];
    }
    if ([lottName isEqualToString:@"11选5"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_11five.png"];
    }
    if ([lottName isEqualToString:@"胜负彩"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_sfc.png"];
    }
    if ([lottName isEqualToString:@"足彩单场"] || [lottName isEqualToString:@"北京单场"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_bd.png"];
    }
    if ([lottName isEqualToString:@"双色球"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_ssq.png"];
    }
    if ([lottName isEqualToString:@"七星彩"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_n7x.png"];
    }
    if ([lottName isEqualToString:@"福彩3D"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_3d.png"];
    }
    if ([lottName isEqualToString:@"七乐彩"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_n7l.png"];
    }
    if ([lottName isEqualToString:@"任选九"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_rx9.png"];
    }
    if ([lottName isEqualToString:@"重庆时时彩"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_ssc.png"];
    }
    if ([lottName isEqualToString:@"大乐透"] || [lottName isEqualToString:@"超级大乐透"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_dlt.png"];
    }
    if ([lottName isEqualToString:@"十一运夺金"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_11ydj.png"];
    }
    if ([lottName isEqualToString:@"排列3"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_p3.png"];
    }
    if ([lottName isEqualToString:@"排列5"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_p5.png"];
    }
    if ([lottName isEqualToString:@"快三"] || [lottName isEqualToString:@"内蒙古快3"]|| [lottName isEqualToString:@"快3"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_k3.png"];
    }
    if ([lottName isEqualToString:@"竞彩篮球"]) {
        self.lotteryImage.image = [UIImage imageNamed:@"jdd_buy_main_jclq.png"];
    }
}
#pragma mark textField的代理
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = self.textFiledBgview.frame;
    [UIView animateWithDuration:0.3 animations:^{
        self.textFiledBgview.frame = CGRectMake(0, frame.origin.y - 160, frame.size.width, frame.size.height);
    } completion:nil];
}

-(void)moveBack
{
        UITextField *textField = (UITextField*)[self.view viewWithTag:100];
        [textField resignFirstResponder];
    
    CGRect frame = self.textFiledBgview.frame;

    [UIView animateWithDuration:0.3 animations:^{
        //获取系统版本号
        self.textFiledBgview.frame =CGRectMake(0, self.view.frame.size.height-55-45, frame.size.width, 45);

    } completion:nil];
}

//放弃所有可能的第一响应 收键盘
-(void)resignAllResponder:(UIView*)parentView
{
    for (UIView *view in parentView.subviews) {
        if ([view isKindOfClass:[UITextField class]]) {
            [self moveBack];
            [view resignFirstResponder];
        }
        else {
            if ([view isKindOfClass:[UIScrollView class]]) {
                [view resignFirstResponder];
            }
            if ([view.subviews count] != 0) {
                [self resignAllResponder:view];
            }
        }
    }
}

//点击结束事件绑定
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self resignAllResponder:self.view];
}
@end
